<template>
  <div>注册</div>
  <el-form ref="registerRef" model="registerForm" rules="rules" label-position="right" status-icon>
    <el-form-item prop="telephone" label="手机号">
      <el-input v-model="registerForm.telephone" />
    </el-form-item>
	<el-form-item prop="verify" label="验证码">
		<el-input v-model="registerForm.verify"  />
		<button @click="getVerificationCode()">获取验证码</button>
	</el-form-item>
    <el-form-item prop="password" label="密码">
      <el-input type="password" v-model="registerForm.pwd" />
    </el-form-item>
	<el-form-item prop="checkpassword" label="确认密码">
	  <el-input type="password" v-model="registerForm.checkpwd" />
	</el-form-item>
    <el-row>
      <el-button @click="toRegister()">注册</el-button>
    </el-row>
  </el-form>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { registerApi } from '../utils/requestApi.js';
import { getVerificationCodeApi } from '../utils/requestApi.js';
import { usePersonStore } from '../store/person.js';

const router = useRouter();
const personStore = usePersonStore();

const registerForm = ref({
  telephone: '15327220037',
  pwd: '',
  checkpwd:'',
  verify: '8524'
});

const registerRef = ref(null);

const rules = {
  telephone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^[1]\d{10}$/, message: '请正确输入11位手机号码', trigger: 'blur' }
  ],
  pwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^\w{3,8}$/, message: '密码为字母或数字3至8位', trigger: 'blur' }
  ],
  checkpwd: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { pattern: /^\w{3,8}$/, message: '密码为字母或数字3至8位', trigger: 'blur' }
  ]
};

const toRegister = () => {
	console.log(registerForm.value)
      registerApi(registerForm.value).then(response => {
        if (response.data.result) {
          ElMessage({
            message: '注册成功',
            type: 'success'
          });
          personStore.setPersonInfo(response.data.data, response.data.msg);
          router.push({ path: '/login' });
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'danger'
          });
        }
      })
      .catch(err => {
        ElMessage({
          message: err,
          type: 'danger'
        });
      });
};

 const getVerificationCode = () => {
   getVerificationCodeApi(registerForm.telephone)
     .then(response => {
       if (response.data.result) {
         ElMessage({
           message: '验证码已发送',
           type: 'success'
         });
       } else {
         ElMessage({
           message: response.data.msg,
           type: 'danger'
         });
       }
     })
     .catch(err => {
       ElMessage({
         message: '获取验证码失败: ' + err.message,
         type: 'danger'
       });
     });
 };
</script>
